<template>
  <div class="blog-detail-container">
    <div class="loading" v-if="loading">
      加载中...
    </div>
    
    <div class="error" v-else-if="error">
      {{ error }}
      <button @click="loadBlog">重新加载</button>
    </div>
    
    <div v-else>
      <article class="blog-post">
        <h1>{{ blog.title }}</h1>
        <div class="blog-meta">
          <span class="author">作者: {{ blog.author }}</span>
          <span class="category">分类: {{ blog.category }}</span>
          <span class="date">发布时间: {{ formatDate(blog.date) }}</span>
        </div>
        <div class="blog-content">
          {{ blog.content }}
        </div>
      </article>
      
      <section class="comments-section">
        <h2>评论 ({{ comments.length }})</h2>
        
        <form @submit.prevent="submitComment" class="comment-form">
          <div class="form-group">
            <label for="commenter">姓名:</label>
            <input 
              id="commenter" 
              v-model="newComment.name" 
              type="text" 
              required 
              placeholder="请输入您的姓名"
            />
          </div>
          
          <div class="form-group">
            <label for="comment-content">评论:</label>
            <textarea 
              id="comment-content" 
              v-model="newComment.content" 
              rows="4" 
              required 
              placeholder="请输入您的评论"
            ></textarea>
          </div>
          
          <div class="button-group">
            <button type="submit" :disabled="isSubmitting">
              {{ isSubmitting ? '提交中...' : '发表评论' }}
            </button>
          </div>
        </form>
        
        <div v-if="commentSubmitError" class="error-message">
          {{ commentSubmitError }}
        </div>
        
        <div v-if="commentSubmitSuccess" class="success-message">
          评论发表成功！
        </div>
        
        <div class="comments-list">
          <div 
            class="comment-item" 
            v-for="comment in comments" 
            :key="comment.id"
          >
            <div class="comment-header">
              <span class="commenter-name">{{ comment.name }}</span>
              <span class="comment-date">{{ formatDate(comment.date) }}</span>
            </div>
            <div class="comment-content">
              {{ comment.content }}
            </div>
          </div>
          
          <div v-if="comments.length === 0" class="no-comments">
            还没有评论，快来抢沙发！
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'

// 定义博客文章和评论的数据结构
interface BlogPost {
  id: number
  title: string
  author: string
  content: string
  category: string
  date: string
}

interface Comment {
  id: number
  name: string
  content: string
  date: string
}

// 获取当前路由参数
const route = useRoute()

// 响应式数据
const blog = ref<BlogPost>({} as BlogPost)
const comments = ref<Comment[]>([])
const loading = ref(true)
const error = ref('')
const isSubmitting = ref(false)
const commentSubmitError = ref('')
const commentSubmitSuccess = ref(false)

// 新评论表单数据
const newComment = reactive({
  name: '',
  content: ''
})

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载博客文章和评论
const loadBlog = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 模拟从API获取数据
    // 实际使用时应该替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 获取博客ID（从路由参数中）
    const blogId = Number(route.params.id) || 1
    
    // 模拟博客数据
    blog.value = {
      id: blogId,
      title: 'Vue 3 入门指南',
      author: '张三',
      content: 'Vue 3 是一款用于构建用户界面的 JavaScript 框架。它基于标准 HTML、CSS 和 JavaScript 构建，并提供了一套声明式的、组件化的编程模型，帮助你高效地开发用户界面。Vue 3 带来了许多新特性，包括 Composition API、更好的 TypeScript 支持、性能提升等。Composition API 是 Vue 3 中最重要的新增功能之一，它允许我们更灵活地组织和复用组件逻辑。与选项式 API 相比，Composition API 提供了更好的代码组织方式，使得大型组件更容易维护。',
      category: '技术',
      date: '2023-01-15'
    }
    
    // 模拟评论数据
    comments.value = [
      {
        id: 1,
        name: '李四',
        content: '这篇文章写得很好，对我很有帮助！',
        date: '2023-01-16'
      },
      {
        id: 2,
        name: '王五',
        content: '感谢分享，期待更多关于Vue 3的文章。',
        date: '2023-01-17'
      }
    ]
  } catch (err) {
    error.value = '加载博客失败'
    console.error('加载博客时出错:', err)
  } finally {
    loading.value = false
  }
}

// 提交新评论
const submitComment = async () => {
  commentSubmitError.value = ''
  commentSubmitSuccess.value = false
  isSubmitting.value = true
  
  try {
    // 模拟提交评论到API
    // 实际使用时应该替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟成功响应
    const comment: Comment = {
      id: comments.value.length + 1,
      name: newComment.name,
      content: newComment.content,
      date: new Date().toISOString()
    }
    
    // 添加到评论列表开头
    comments.value.unshift(comment)
    
    // 重置表单
    newComment.name = ''
    newComment.content = ''
    
    // 显示成功消息
    commentSubmitSuccess.value = true
    
    // 3秒后隐藏成功消息
    setTimeout(() => {
      commentSubmitSuccess.value = false
    }, 3000)
  } catch (err) {
    commentSubmitError.value = '评论发表失败，请重试'
    console.error('提交评论时出错:', err)
  } finally {
    isSubmitting.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadBlog()
})
</script>

<style scoped>
.blog-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.loading, .error {
  text-align: center;
  padding: 40px 20px;
  font-size: 18px;
}

.error {
  color: #d32f2f;
}

.error button {
  margin-left: 10px;
  padding: 8px 16px;
  background-color: #d32f2f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 博客文章样式 */
.blog-post h1 {
  color: #333;
  margin-bottom: 10px;
}

.blog-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #666;
}

.blog-content {
  line-height: 1.8;
  color: #444;
  white-space: pre-wrap;
}

/* 评论区域样式 */
.comments-section {
  margin-top: 50px;
}

.comments-section h2 {
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.comment-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.button-group {
  text-align: center;
}

button {
  padding: 12px 30px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #0056b3;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.error-message {
  padding: 10px;
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  text-align: center;
  margin-bottom: 20px;
}

.success-message {
  padding: 10px;
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
  border-radius: 4px;
  text-align: center;
  margin-bottom: 20px;
}

/* 评论列表样式 */
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  background-color: #fafafa;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.commenter-name {
  font-weight: bold;
  color: #333;
}

.comment-date {
  color: #888;
}

.comment-content {
  color: #555;
  line-height: 1.6;
}

.no-comments {
  text-align: center;
  padding: 30px;
  color: #888;
  font-style: italic;
}
</style>